<template>
  <el-drawer
    title="聊天记录"
    size="40%"
    :visible.sync="visible"
    direction="rtl"
    show-close
		:modal="false"
		:wrapperClosable="false"
    :before-close="onClose"
    :modal-append-to-body="false"
  >
    <div
      class="chat-history"
      v-loading="loading"
      element-loading-text="拼命加载中"
    >

      <div class="search-box">
        <el-input
          v-model="searchText"
          placeholder="搜索聊天记录"
          clearable
          size="small"
        >
				<i slot="prefix" class="el-input__icon el-icon-search"></i>
				</el-input>
      </div>
      
      <el-scrollbar
        class="chat-history-scrollbar"
        ref="scrollbar"
        id="historyScrollbar"
      >
        <ul>
          <li v-for="(msgInfo, idx) in filteredMessages" :key="idx">
            <chat-message-item
              :mode="2"
              :mine="false"
              :headImage="headImage(msgInfo)"
              :showName="showName(msgInfo)"
              :msgInfo="msgInfo"
              :menu="false"
							:historyMode="true"
							@locate="handleLocate"
            >
            </chat-message-item>
          </li>
          <!-- 没有搜索结果时显示提示 -->
          <li v-if="searchText && filteredMessages.length === 0" class="no-results">
            未找到与 "{{ searchText }}" 相关的聊天记录
          </li>
          <!-- 没有消息时显示提示 -->
          <li v-else-if="!searchText && chat.messages.length === 0" class="no-results">
            暂无聊天记录
          </li>
        </ul>
      </el-scrollbar>
    </div>
  </el-drawer>
</template>

<script>
import ChatMessageItem from './ChatMessageItem.vue'

export default {
  name: 'chatHistory',
  components: {
    ChatMessageItem
  },
  props: {
    visible: {
      type: Boolean
    },
    chat: {
      type: Object
    },
    friend: {
      type: Object
    },
    group: {
      type: Object
    },
    groupMembers: {
      type: Array
    }
  },
  data() {
    return {
      page: 1,
      size: 10,
      messages: [],
      loadAll: false,
      loading: false,
      lastScrollTime: new Date(),
      searchText: '' // 搜索文本
    }
  },
  computed: {
    mine() {
      return this.$store.state.userStore.userInfo
    },
    histroyAction() {
      return `/message/${this.chat.type.toLowerCase()}/history`
    },
    filteredMessages() {
      if (!this.searchText) {
        return this.chat.messages;
      }
      
      const keyword = this.searchText.toLowerCase();
      return this.chat.messages.filter(msg => {
        // 检查消息内容是否包含关键词
        if (msg.content && msg.content.toLowerCase().includes(keyword)) {
          return true;
        }
        // 检查发送者名称是否包含关键词
        const senderName = this.showName(msg).toLowerCase();
        if (senderName && senderName.includes(keyword)) {
          return true;
        }
        return false;
      });
    }
  },
  methods: {
		handleLocate(id) {
      this.$emit('locate', id)
    },
    onClose() {
      this.page = 1
      this.messages = []
      this.loadAll = false
      this.searchText = '' // 清空搜索文本
      this.$emit('close')
    },
    onScroll() {
      let high = this.$refs.scrollbar.$refs.wrap.scrollTop //距离顶部的距离
      let timeDiff = new Date().getTime() - this.lastScrollTime.getTime()
      if (high < 30 && timeDiff > 500) {
        this.lastScrollTime = new Date()
        // this.loadMessages();
      }
    },
    loadMessages() {
      if (this.loadAll) {
        return this.$message.success('已到达顶部')
      }
      let param = {
        page: this.page++,
        size: this.size
      }
      if (this.chat.type == 'GROUP') {
        param.groupId = this.group.id
      } else {
        param.friendId = this.friend.id
      }
      this.loading = true
      this.$http({
        url: this.histroyAction,
        method: 'get',
        params: param
      })
        .then((messages) => {
          messages.forEach((m) => this.messages.unshift(m))
          this.loading = false
          if (messages.length < this.size) {
            this.loadAll = true
          }
          this.refreshScrollPos()
        })
        .catch(() => {
          this.loading = false
        })
    },
    showName(msgInfo) {
      if (this.chat.type == 'GROUP') {
        let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId)
        return member ? member.showNickName : ''
      } else {
        return msgInfo.sendId == this.mine.id
          ? this.mine.nickName
          : this.chat.showName
      }
    },
    headImage(msgInfo) {
      if (this.chat.type == 'GROUP') {
        let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId)
        return member ? member.headImage : ''
      } else {
        return msgInfo.sendId == this.mine.id
          ? this.mine.headImageThumb
          : this.chat.headImage
      }
    },
    refreshScrollPos() {
      let scrollWrap = this.$refs.scrollbar.$refs.wrap
      let scrollHeight = scrollWrap.scrollHeight
      let scrollTop = scrollWrap.scrollTop
      this.$nextTick(() => {
        let offsetTop = scrollWrap.scrollHeight - scrollHeight
        scrollWrap.scrollTop = scrollTop + offsetTop
        // 滚动条没出来，继续加载
        if (scrollWrap.scrollHeight == scrollHeight) {
          // this.loadMessages();
        }
      })
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const scrollContainer = document.getElementById('historyScrollbar')
        if (scrollContainer) {
          const wrap = scrollContainer.querySelector('.el-scrollbar__wrap')
          if (wrap) {
            wrap.scrollTop = wrap.scrollHeight
          }
        }
      })
    }
  },
  watch: {
    visible: {
      handler(newValue, oldValue) {
        if (newValue) {
          // this.loadMessages();
          this.$nextTick(() => {
            document
              .getElementById('historyScrollbar')
              .addEventListener('mousewheel', this.onScroll, true)
            this.scrollToBottom();
          })
        }
      }
    },
    // 监听搜索文本变化
    searchText(newVal, oldVal) {
      // 当清空搜索内容时，自动滚动到底部
      if (!newVal && oldVal) {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    }
  }
}
</script>

<style lang="scss">
.chat-history {
  display: flex;
  height: 100%;
  flex-direction: column;

  .search-box {
    padding: 10px 20px 10px 20px;
  }

  .chat-history-scrollbar {
    flex: 1;
    .el-scrollbar__thumb {
      background-color: #555555;
    }
    ul {
      padding: 20px;

      li {
        list-style-type: none;
      }
      
      .no-results {
        text-align: center;
        color: #999;
        padding: 20px 0;
      }
    }
  }
}

.search-box{
	.el-icon-search{
		color:#c0c4cc !important;
	}
}
</style>

<style lang="scss" scoped>
:deep(.el-dialog__close) {
  color: #72767b !important;
}
:deep(.chat-msg-item .chat-msg-normal .chat-msg-content .chat-msg-bottom) {
  padding: 0;
}
:deep(.el-drawer__header){
  margin-bottom: 15px;
}

</style>